package cn.tedu.knows.faq.service.imp;

import cn.tedu.knows.commons.exception.ServiceException;
import cn.tedu.knows.commons.model.Comment;
import cn.tedu.knows.commons.model.User;
import cn.tedu.knows.faq.mapper.CommentMapper;
import cn.tedu.knows.faq.service.ICommentService;
import cn.tedu.knows.faq.vo.CommentVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2021-10-27
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {


    @Autowired
    private CommentMapper commentMapper;

    @Resource
    private RibbonClient ribbonClient;


    @Override
    @Transactional
    public Comment saveComment(CommentVo commentVo, String username) {
        User user = ribbonClient.getUser(username);
        Comment comment = new Comment()
                .setUserId(user.getId())
                .setUserNickName(user.getNickname())
                .setAnswerId(commentVo.getAnswerId())
                .setContent(commentVo.getContent())
                .setCreatetime(LocalDateTime.now());

        int num = commentMapper.insert(comment);
        if (num !=1) {
            throw new ServiceException("数据库异常");
        }
        return comment;
    }

    @Override
    @Transactional
    public boolean removeComment(Integer commentId, String username) {
        User user = ribbonClient.getUser(username);
        //判断是不是讲师,如果是可以删除任何评论
        if (user.getType().equals(1)){
            int num = commentMapper.deleteById(commentId);
            return num==1;
        }
        //如果是学生要判断评论的发布者id是否和当前登录用户id一致
        Comment comment = commentMapper.selectById(commentId);
        if (comment.getUserId().equals(user.getId())){
            //如果一致 执行删除
            int num= commentMapper.deleteById(commentId);
            return num==1;
        }
        throw new ServiceException("不能删除他人评论");

    }

    @Override
    @Transactional
    public Comment updateComment(Integer commentId, CommentVo commentVo, String username) {
        //和删除评论一样,讲师随意修改,学生只能修改自己的评论
        User user = ribbonClient.getUser(username);
        Comment comment = commentMapper.selectById(commentId);

        //如果是讲师,或者是评论的发布者
        if (user.getType().equals(1) ||
        comment.getUserId().equals(user.getId())){
            //执行修改:只能修改内容
            comment.setContent(commentVo.getContent());
            //修改提交数据库
            int num = commentMapper.updateById(comment);
            if (num!=1){
                throw new ServiceException("服务器忙!");
            }
            return comment;
        }
        throw new ServiceException("不能修改别人的评论");
    }
}
